<template>
    <view>
        <!-- 搜索区域 -->
        <view class="search">
            <view class="uni-form-item">
                <input class="uni-input custom-input" confirm-type="search" placeholder="请输入商品类型厂家等关键字查询"
                    v-model="searchKey" @confirm="getpageList" />
            </view>
            <u-button @click="getpageList" class="searchBtn" text="搜索"
                color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"></u-button>
        </view>

        <!-- 瀑布流布局 -->
        <view class="waterfall-container">
            <view class="waterfall-column left-column">
                <view v-for="(item, index) in leftColumn" :key="item.id || index" class="waterfall-item"
                    @click="productBtn(item)">
                    <view class="image-container" :style="{height: imageHeight + 'rpx'}">
                        <image v-if="item.cargo==0" :src="getImageSource(item) || defaultImage" mode="aspectFill"
                            @error="(e) => handleImageError(e, item)" class="full-width-image"></image>
                        <image v-if="item.cargo==1" src="@/static/nomore.png" class="full-width-image nomoreImg">
                        </image>
                        <view v-if="!getImageSource(item)" class="no-image-placeholder">
                            <text>暂无图片</text>
                        </view>
                    </view>
                    <view class="item-info">
                        <text class="item-title">{{ item.name }}-{{item.manufactureName}}</text>
                        <text class="item-price">¥{{ item.price }}/米</text>
                    </view>
                </view>
            </view>

            <view class="waterfall-column right-column">
                <view v-for="(item, index) in rightColumn" :key="item.id || index" class="waterfall-item"
                    @click="productBtn(item)">
                    <view class="image-container" :style="{height: imageHeight + 'rpx'}">
                        <image :src="getImageSource(item) || defaultImage" mode="aspectFill"
                            @error="(e) => handleImageError(e, item)" class="full-width-image"></image>
                        <view v-if="!getImageSource(item)" class="no-image-placeholder">
                            <text>暂无图片</text>
                        </view>
                    </view>
                    <view class="item-info">
                        <text class="item-title">{{ item.name }}-{{item.manufactureName}}</text>
                        <text class="item-price">¥{{ item.price }}/米</text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 加载提示 -->
        <view class="loading-tip" v-if="loading">加载中...</view>
        <view class="loading-tip" v-if="noMore">没有更多了</view>
        
        <!-- 触底加载区域 -->
        <view class="load-more-trigger" @scrolltolower="loadMore"></view>
    </view>
</template>

<script>
import request from '@/utils/request';

export default {
    data() {
        return {
            searchKey: '',
            current: 1,
            size: 10,
            loading: false,
            noMore: false,
            pageList: [],
            leftColumn: [],
            rightColumn: [],
            screenWidth: 0,
            columnWidth: 0,
            defaultImage: '/static/default-image.png',
            imageHeight: 300, // 固定图片高度
            itemHeight: 360, // 固定项目总高度 (图片+信息区)
            infoHeight: 60, // 信息区高度
            triggerDistance: 100 // 距离底部多少距离触发加载
        };
    },

    onLoad() {
        const info = uni.getSystemInfoSync();
        this.screenWidth = info.windowWidth;
        this.columnWidth = (this.screenWidth - 40) / 2; // 调整间距计算
        this.getpageList();
    },
    
    onReachBottom() {
        // 页面触底时加载更多
        this.loadMore();
    },
    
    onPullDownRefresh() {
        console.log('触发下拉刷新');
        this.getpageList(); // 调用刷新数据的方法
    },
    
    methods: {
        // 商品详情页
        productBtn(index) {
            console.log(index, '点击商品详情');
            // 商品详情跳转id查询暂无
            // uni.navigateTo({
            //   url: `/pages/detail/detail?id=${encodeURIComponent(JSON.stringify(index.id))}`
            // });
            uni.navigateTo({
                url: `/pages/detail/detail?name=${encodeURIComponent(JSON.stringify(index.name))}`
            });
        },
        
        // 新增方法：安全获取图片源
        getImageSource(item) {
            if (!item || !item.flatPatternmaking || !Array.isArray(item.flatPatternmaking) || item.flatPatternmaking.length === 0) {
                return null;
            }
            return item.flatPatternmaking[0].ossUrl;
        },

        async getpageList() {
            // 重置分页和状态
            this.current = 1;
            this.loading = true;
            this.noMore = false;

            try {
                const result = await request.get('/api/boke/v1/item/page', {
                    current: this.current,
                    size: this.size,
                    name: this.searchKey
                }, {});
                
                this.pageList = result.records || [];
                // 停止下拉刷新动画
                uni.stopPullDownRefresh();
                this.splitItemsToColumns();
                this.noMore = this.pageList.length < this.size;
            } catch (error) {
                uni.removeStorageSync('token');
                console.error('获取数据失败:', error);
            } finally {
                this.loading = false;
            }
        },

        async loadMore() {
            // 如果正在加载或者没有更多数据，则不执行
            if (this.loading || this.noMore) return;
            
            this.loading = true;
            
            try {
                // 计算下一页页码
                const nextPage = Math.ceil(this.pageList.length / this.size) + 1;
                
                const result = await request.get('/api/boke/v1/item/page', {
                    current: nextPage,
                    size: this.size,
                    name: this.searchKey
                });
                
                const newItems = result.records || [];
                
                if (newItems.length > 0) {
                    // 追加新数据
                    this.pageList = [...this.pageList, ...newItems];
                    this.splitItemsToColumns();
                    
                    // 更新当前页码
                    this.current = nextPage;
                }
                
                // 判断是否还有更多数据
                this.noMore = newItems.length < this.size;
            } catch (error) {
                console.error('加载更多失败:', error);
            } finally {
                this.loading = false;
            }
        },

        // 简化的瀑布流分割算法
        splitItemsToColumns() {
            const left = [];
            const right = [];

            this.pageList.forEach((item, index) => {
                if (index % 2 === 0) {
                    left.push(item);
                } else {
                    right.push(item);
                }
            });

            this.leftColumn = left;
            this.rightColumn = right;
        },

        handleImageError(e, item) {
            console.error(`图片加载错误 - 商品ID: ${item.id || '未知'}`, e);
            // 无需处理高度，已使用固定高度
        },

        clickItem(item) {
            console.log('点击商品:', item);
            uni.navigateTo({
                url: `/pages/product/detail?id=${item.id}`
            });
        }
    }
};
</script>

<style lang="scss">
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

// 搜索区域样式
.search {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    margin: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .uni-form-item {
        flex: 1;
        height: 72rpx;
        padding: 0 20rpx;
        border: #dcd8d8 1px solid;
        border-radius: 36rpx;
        margin-right: 16rpx;
        display: flex;
        align-items: center;

        .custom-input {
            flex: 1;
            height: 68rpx;
            line-height: 68rpx;
            font-size: 28rpx;
            padding: 0 12rpx;
            border: none;
            background-color: transparent;
            color: #333;
        }
    }

    .searchBtn {
        width: 140rpx;
        height: 72rpx;
        line-height: 72rpx;
        border-radius: 36rpx;
        font-size: 28rpx;
    }
}

// 瀑布流容器
.waterfall-container {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-between;
    padding: 0 16rpx;
    background-color: #f5f5f5;
    width: 100%;
    box-sizing: border-box;
}

// 瀑布流列
.waterfall-column {
    width: 48%;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

// 瀑布流项目
.waterfall-item {
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    display: flex;
    flex-direction: column;
}

// 图片容器
.image-container {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    background-color: #f8f8f8;
}

// 图片样式 - 强制铺满
.full-width-image {
    width: 100% !important;
    height: 100% !important;
    object-fit: cover !important;
    display: block;
}

// 无图占位样式
.no-image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f8f8f8;
    color: #bbb;
    font-size: 26rpx;
}

// 商品信息
.item-info {
    padding: 16rpx;
    border-top: 1px solid #f5f5f5;
}

// 商品标题
.item-title {
    font-size: 26rpx;
    color: #333;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 8rpx;
}

// 商品价格
.item-price {
    font-size: 30rpx;
    color: #e64340;
    font-weight: bold;
}

// 加载提示
.loading-tip {
    text-align: center;
    padding: 30rpx 0;
    font-size: 28rpx;
    color: #999;
}

// 触底加载区域
.load-more-trigger {
    height: 50rpx;
}
</style>    